package prj.stars;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * Adapter for members of a group: add, remove, display.
 * 
 * @author Andreea-Cristina Hodea
 *
 */
public class GroupAdapter extends BaseAdapter{
	
	private Activity context;
	private ArrayList<GroupMember> students;
	
	public GroupAdapter(Activity context) {
		this.context = context;
		students = new ArrayList<GroupMember>();
	}
	
	public int getCount() {
		return students.size();
	}

	public Object getItem(int position) {
		if (position >= 0 && position < students.size())
			return students.get(position);
		return null;
	}

	public long getItemId(int position) {
		return 0;
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		View elem;
		if (convertView == null) {
			LayoutInflater inflater = context.getLayoutInflater();
			elem = inflater.inflate(R.layout.studentdata, null);
		}
		else elem = convertView;
		
		GroupMember student = students.get(position);

		ImageView image = (ImageView)elem.findViewById(R.id.star);
		if (student.getStars() == 0)
			image.setImageResource(R.drawable.empty);
		else image.setImageResource(R.drawable.star);
		
		
        TextView tv;
        tv = (TextView)elem.findViewById(R.id.studentName);
        tv.setText(student.getStudent());
        tv = (TextView)elem.findViewById(R.id.studentStars);
        tv.setText(" x " + student.getStars());
        tv = (TextView)elem.findViewById(R.id.studentPresence);
        tv.setText("" + student.getPresence());
        tv = (TextView)elem.findViewById(R.id.studentGrade);
        tv.setText("" + (new DecimalFormat("#.##").format(student.getGrade())));
        
		return elem;
	}
	
	public boolean addGroupMember(GroupMember student) {
		if (!students.contains(student)) {
			students.add(student);
			Collections.sort(students);
			this.notifyDataSetChanged();
			return true;
		}
		return false;
	}
	
	public boolean removeGroupMember(GroupMember student) {
		boolean removed =  students.remove(student);
		if (removed)
			this.notifyDataSetChanged();
		return removed;
	}
	
	public void edit() {
		this.notifyDataSetChanged();
	}

}
